package com.kangaroo.csv;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liubo
 * @ClassName Loader
 * @Description TODO
 * @Date 2020/10/17
 * @since JDK 1.8
 */
class Loader extends CSVBaseListener {
    public static final String EMPTY = "";

    int i=0;
    /**
     * Load a list of row maps that map field name to value
     */
    List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
    /**
     * List of column names
     */
    List<String> header;
    /**
     * Build up a list of fields in current row
     */
    List<Object> currentRowFieldValues;

    public void exitString(CSVParser.StringContext ctx) {
        System.out.println(String.valueOf(i++)+":"+"exitString");
        String t=ctx.STRING().getText();
        currentRowFieldValues.add(t.replace("\"",""));
    }
    public void exitText(CSVParser.TextContext ctx) {
        String t=ctx.TEXT().getText();
        System.out.println(String.valueOf(i++)+":"+"exitText");
        currentRowFieldValues.add(ctx.TEXT().getText());
    }
    public void exitEmpty(CSVParser.EmptyContext ctx) {
        currentRowFieldValues.add(EMPTY);
    }

    /**
     * {@inheritDoc}
     *
     * <p>The default implementation does nothing.</p>
     */
    @Override
    public void enterFile(CSVParser.FileContext ctx) {
        System.out.println(String.valueOf(i++)+":"+"enterFile");
    }
    /**
     * {@inheritDoc}
     *
     * <p>The default implementation does nothing.</p>
     */
    @Override public void exitFile(CSVParser.FileContext ctx) {
        System.out.println(String.valueOf(i++)+":"+"exitFile");
    }

    public void exitHdr(CSVParser.HdrContext ctx) {
        System.out.println(String.valueOf(i++)+":"+"exitHdr");
        header = new ArrayList<String>();
        for(Object v:currentRowFieldValues){
            header.add(v.toString());
        }
        System.out.println(String.valueOf(i++)+":"+"exitHdr");
    }
    public void enterRow(CSVParser.RowContext ctx) {
        System.out.println(String.valueOf(i++)+":"+"enterRow");
        currentRowFieldValues = new ArrayList<Object>();
    }
    public void exitRow(CSVParser.RowContext ctx) {
        System.out.println(String.valueOf(i++)+":"+"exitRow");
        // If this is the header row, do nothing
        // if ( ctx.parent instanceof CSVParser.HdrContext ) return; OR:
        if ( ctx.getParent().getRuleIndex() == CSVParser.RULE_hdr ) return;
        // It's a data row
        Map<String, Object> m = new LinkedHashMap<String, Object>();
        int i = 0;
        for (Object v : currentRowFieldValues) {
            m.put(header.get(i), v);
            i++;
        }
        rows.add(m);
    }

}